<template>
  <div
    class="TheWidget"
    :style="style"
    :data-id="config.id"
    :data-top="config.top"
    :data-left="config.left"
    :data-width="config.wdith"
  >
    <QhCard :title="title" type="small">
      <div ref="chart" class="chart"></div>
    </QhCard>
  </div>
</template>
<script>
import echarts from "echarts"
import lodash from "lodash"
const initOption = () => {
  return {
    grid: {
      show: true,
      top: 20,
      bottom: 20,
      backgroundColor: "rgba(0, 0, 0, 0)",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: "line",
      },
    ],
  }
}

export default {
  name: "TheLineChart",
  props: {
    config: {
      type: Object,
      required: true,
    },
    dimension: {
      type: Object,
      required: true,
    },
  },
  computed: {
    style() {
      return {
        top: this.dimension.top + "px",
        left: this.dimension.left + "px",
        width: this.dimension.width + "px",
        height: this.dimension.height + "px",
      }
    },
    option() {
      return this.config.chartOption || {}
    },
    title() {
      return this.config.title ? this.config.title : "未命名" + this.config.id
    },
  },
  watch: {
    "dimension.width"() {
      this.resize()
    },
    "dimension.height"() {
      this.resize()
    },
    option: {
      deep: true,
      handler() {
        console.log("chart init")
        this.init()
      },
    },
  },
  methods: {
    init() {
      if (this.$refs.chart || !this.chart) {
        this.chart = echarts.init(this.$refs.chart)
        this.chart.setOption(lodash.merge(initOption(), this.option))
      }
    },
    resize() {
      if (this.$refs.chart && this.$refs.chart.offsetHeight && this.chart) {
        this.chart.resize()
      }
    },
  },
  mounted() {
    this.init()
    window.addEventListener("resize", () => {
      this.resize()
    })
  },
}
</script>

<style lang="scss">
.TheWidget .chart {
  width: 100%;
  height: 100%;
}
</style>
